package com.itheima.ai.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/deepseek")
@RequiredArgsConstructor
@Slf4j
public class DeepSeekChatController {


    private final ChatClient chatClient;


    /**
     * ChatClient 普通调用 ai输出上下文后得到响应
     * @param message
     * @return
     */
    @GetMapping(value = "/ai/chat")
    public String chatApi(@RequestParam("message") String message) {
        log.info("message: {}", message);
        return chatClient.prompt()
                .user(message)
                .call()
                .content();

    }



    @GetMapping("/stream/chat")
    public Flux<String> streamChat(@RequestParam String message,
                                   HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        log.info("收到流式聊天请求，入参: {}", message);

        response.setCharacterEncoding("UTF-8");
        return chatClient.prompt(message).stream().content()
                .doOnNext(content -> log.debug("流式响应内容: {}", content))
                .doOnComplete(() -> log.info("流式聊天完成，入参: {}, 总耗时: {} ms",
                        message, System.currentTimeMillis() - startTime))
                .doOnError(error -> log.error("流式聊天异常，入参: {}, 异常信息: {}, 总耗时: {} ms",
                        message, error.getMessage(), System.currentTimeMillis() - startTime));
    }


    /**
     * ChatClient 流式响应
     */
    @GetMapping(value = "/stream/response", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat(@RequestParam String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .content()
                .map(content -> ServerSentEvent.<String>builder()
                        .data(content)
                        .build());
    }
}

